package demo.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import demo.security.handler.DemoAuthenticationFailureHandler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

	final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Bean
	@Override
	public UserDetailsService userDetailsService() {
		return new UserDetailsService() {
			@Override
			public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
				String[] roles;
				if (username.startsWith("user")) {
					roles = new String[] { "USER" };
				} else if (username.startsWith("admin")) {
					roles = new String[] { "USER", "ADMIN" };
				} else {
					roles = new String[] { username.toUpperCase() };
				}
				return User.withDefaultPasswordEncoder().username(username).password(username).roles(roles).build();
			}
		};
	}

	@Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
////		web.ignoring().antMatchers("/token_key");
//		web.ignoring().antMatchers("/token_key","/error","/login"); 
//		web.ignoring().antMatchers("/resources/**","/static/**");
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {	
		// @formatter:off
		logger.debug("***WebSecurityConfiguration: WebSecurityConfigurerAdapter.configure(HttpSecurity http): {}", http);
		String loginPageUrl = "/login";	
		
		http
			.authorizeRequests().antMatchers(loginPageUrl).permitAll().and()
			.authorizeRequests().anyRequest().authenticated().and()
			.formLogin()
				.loginPage(loginPageUrl)
				.failureHandler(new DemoAuthenticationFailureHandler(loginPageUrl))
			.and()
			.httpBasic();		
		// @formatter:on
	}
}
